package net.sunzc.yunlian.view;

import com.android.ddmlib.Log;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.layout.FlowPane;
import net.sunzc.yunlian.controller.DeviceController;

import java.net.URL;
import java.util.LinkedHashMap;
import java.util.ResourceBundle;

/**
 * Created by Sun on 2016/6/5.
 */
public class MainWindow implements Initializable, DeviceController.ScreenListener {
    private static final String TAG = "MainWindow";
    private static LinkedHashMap<String, net.sunzc.yunlian.view.ScreenWindow> screenMap = new LinkedHashMap<>();
    public FlowPane flowPane;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Log.i(TAG, "初始化");
        updateNumber();
        DeviceController.startADB().setScreenListener(this);
    }

    private void updateNumber() {
        flowPane.getChildren().addListener(new ListChangeListener<Node>() {
            @Override
            public void onChanged(Change<? extends Node> c) {
                ObservableList<? extends Node> list = c.getList();
                for (Node node : list) {
                    if (node instanceof AndroidScreen) {
                        int index = list.indexOf(node);
                        ((AndroidScreen) node).updateScreenNumber(index + 1);
                    }
                }
            }
        });
    }

    @Override
    public void addScreen(ScreenWindow screenWindow) {
        flowPane.getChildren().add(screenWindow);
        screenMap.put(screenWindow.getSerialNum(), screenWindow);
    }

    @Override
    public void removeScreen(ScreenWindow screen) {
        ScreenWindow screenWindow = screenMap.remove(screen.getSerialNum());
        flowPane.getChildren().remove(screenWindow);
        screenWindow.stop();
    }

}
